<?php
/**
 * Created by PhpStorm.
 * User: 93195
 * Date: 2018/7/16
 * Time: 16:21
 */
class QuanRegisterDataModel extends Model
{
    private $dataModel = null;
    private $customerId = null;

    public function __construct()
    {
        $this->customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $this->dataModel = M('quan_register_data');
        Session::switchCustomer($this->customerId);
    }

    /**新建或修改注册项
     * @param string $id 修改的时候传
     * @param string $name 名称
     * @param string $icon 图标
     * @param string $description 描述
     * @param string $type 类型
     * @return bool|mixed|string
     */
    public function operateRegisterData($id = '', $name, $icon, $descript, $type, $must)
    {
        $data = [
            'cid' => $this->customerId,
            'name' => $name,
            'icon' => $icon,
            'descript' => $descript,
            'type' => $type,
            'must' => $must,
            'updateTime' => date('Y-m-d H:i:s', time())
        ];

        if (empty($id)) {
            $data['createTime'] = date('Y-m-d H:i:s', time());
            $res = $this->dataModel->add($data);
            $id = $res;
        } else {
            $cid = $this->dataModel->where(['id' => $id])->getField('cid');
            if ($cid == 0) return 'default'; //默认的项不允许修改
            $res = $this->dataModel->where(['id' => $id])->save($data);
        }

        if (is_numeric($res)) {
            return $id;
        } else {
            return false;
        }
    }

    /**删除
     * @param $id
     * @return bool
     */
    public function deleteRegisterDataById($id)
    {
        $data = [
            'deleted' => 1,
            'deleteTime' => date('Y-m-d H:i:s', time())
        ];
        $cid = $this->dataModel->where(['id' => $id])->getField('cid');
        if ($cid == 0) return 'default'; //默认的项不允许删除
        return $this->dataModel->where(['id' => $id])->save($data);
    }

    /**列表
     * @param $start
     * @param $limit
     * @param int $type 0-包含默认项，1-不包含默认项
     * @param array $where
     * @return array
     */
    public function registerDataList($start, $limit, $type, $where = [])
    {
        $type ? $where['cid'] = $this->customerId : $where['_string'] = "cid = $this->customerId or cid = 0";
        $where['deleted'] = 0;

        $result = $this->dataModel->where($where)->limit($start, $limit)->select();
        $count = $this->dataModel->where($where)->count();
        if (empty($result)) $result = [];
        return [
            'code' => 0,
            'data' => $result,
            'total' => $count
        ];
    }

    public function getRegisterData($where)
    {
        return $this->dataModel->where($where)->find();
    }
}